package org.zebra.mybatis.plus.core;

import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.zebra.common.core.BaseResponseBodyAdviceChain;
import org.zebra.common.core.Result;

import java.util.HashMap;
import java.util.Map;

/**
 * mybatisplus 分页规范化输出
 *
 * @author zhanghongbin
 */
public class MybatisPlusBaseResponseBodyAdviceChain extends BaseResponseBodyAdviceChain {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(
            Object body,
            MethodParameter returnType,
            MediaType selectedContentType,
            Class<? extends HttpMessageConverter<?>> selectedConverterType,
            ServerHttpRequest request,
            ServerHttpResponse response) {
        if (returnType.getParameterType().isAssignableFrom(IPage.class)) {
            Result result = (Result) body;
            IPage ipage = (IPage) result.getData();
            Map<String, Object> r = new HashMap<>();
            r.put("total", ipage.getTotal());
            r.put("size", ipage.getSize());
            r.put("current", ipage.getCurrent());
            r.put("pages", ipage.getPages());
            r.put("records", ipage.getRecords());
            result.setData(r);
            return result;
        }
        return body;
    }
}
